package com.shinewind.info.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shinewind.info.mapper.IUserSaveMapper;
import com.shinewind.info.service.IUserSaveService;
import com.shinewind.pojo.dto.PageDto;
import com.shinewind.pojo.entity.UserSave;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserSaveServiceImpl extends ServiceImpl<IUserSaveMapper, UserSave> implements IUserSaveService {
    @Override
    public List<Integer> getaIdByuId(String uId, PageDto pageDto) {
        List<UserSave> userSaves = this.lambdaQuery().eq(UserSave::getUId,uId)
                .page(new Page<>(pageDto.getCurrentPage(), pageDto.getPageSize())).getRecords();
        //按id查询所有被收藏的文章的id
        List<Integer> aIdList = userSaves.stream().map(userSave -> {
            return userSave.getAId();
        }).collect(Collectors.toList());
        return aIdList;
    }

    @Override
    public Long getaIdCount(String uId) {
        Long total = this.lambdaQuery().eq(UserSave::getUId,uId).count();
        return total;
    }

    @Override
    public String saveArticleByaIdANDuId(Integer aId, String uId) {
        System.out.println("aId:"+aId);
        System.out.println("uId:"+uId);
        //如果已经收藏了该文章
        if(this.lambdaQuery().eq(UserSave::getAId,aId).eq(UserSave::getUId,uId).count() > 0){
            return "你已经收藏了该文章了,请不要重复操作";
        }
        //未收藏该文章,允许添加
        else if(this.lambdaQuery().eq(UserSave::getAId,aId).eq(UserSave::getUId,uId).count() == 0){
            UserSave userSave = UserSave.builder().aId(aId).uId(uId).build();
            return this.save(userSave) == true ? "收藏成功" : "收藏失败";
        }
        return "未知错误";
    }

    @Override
    public Boolean deleteSaveArticleByAidANDUid(Integer aId, String uId) {
        return this.lambdaUpdate().eq(UserSave::getAId,aId).eq(UserSave::getUId,uId).remove();
    }
}
